package servlet;

import model.Todo;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;
import service.TodoService;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet("")
public class TodoPage extends HttpServlet {
    private final TodoService todoService = new TodoService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext servletContext = req.getServletContext();
        TemplateEngine engine = (TemplateEngine)servletContext.getAttribute("engine");
        try {
            String todo = req.getParameter("todo");
            if (todo != null){
                todoService.save(todo);
            }


            List<Todo> todoList = todoService.query();
            WebContext context = new WebContext(req, resp, servletContext);
            context.setVariable("todoList", todoList);

            resp.setCharacterEncoding("utf-8");
            resp.setContentType("text/html");
            engine.process("todo", context, resp.getWriter());
        } catch (SQLException exc) {
            throw new ServletException(exc);
        }
    }
}
